package com.boby.homecamera.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.boby.homecamera.R
import com.boby.homecamera.adapter.CameraDeviceAdapter.CameraDeviceViewHolder
import com.boby.homecamera.db.CameraDeviceTable
import com.boby.homecamera.net.Api
import com.bumptech.glide.Glide
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.load.model.LazyHeaders
import com.bumptech.glide.signature.ObjectKey

class CameraDeviceAdapter(var data: MutableList<CameraDeviceTable.CameraDevice>): RecyclerView.Adapter<CameraDeviceViewHolder>() {
    private var operationClickListener: ((view:View,position: Int,item:CameraDeviceTable.CameraDevice)->Unit ?)? = null
    private var itemClickListener: ((item:CameraDeviceTable.CameraDevice)->Unit ?)? = null
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CameraDeviceViewHolder {
      val view =  LayoutInflater.from(parent.context).inflate(R.layout.item_camera_device,parent,false)
        return CameraDeviceViewHolder(view)
    }

    override fun onBindViewHolder(holder: CameraDeviceViewHolder, position: Int) {
        val item = data[position]
        holder.tv_deviceName.setText(item.deviceName)
        holder.itemView.setOnClickListener {
            itemClickListener?.invoke(item)
        }
        holder.iv_operation.setOnClickListener {
            operationClickListener?.invoke(holder.iv_operation,position,item)
        }

        val url = GlideUrl(
            "${Api.getRealUrl(item.ip,item.httpPort)}/video/lastpic",
            LazyHeaders.Builder()
                .addHeader("Authorization", "Bearer ${item.token}")
                .build()
        )

        Glide.with(holder.iv_camera_preview)
            .load(url)
            .signature(ObjectKey(System.currentTimeMillis()))
            .into(holder.iv_camera_preview)
    }

    override fun getItemCount(): Int {
      return  data.size
    }

    fun setOperationClickListener(listener: (view:View,position: Int,item:CameraDeviceTable.CameraDevice) -> Unit ){
        this.operationClickListener = listener
    }
    fun setItemClickListener(listener: (item:CameraDeviceTable.CameraDevice) -> Unit ){
        this.itemClickListener = listener
    }

    class CameraDeviceViewHolder(var itemView:View):ViewHolder(itemView){
        val tv_deviceName = itemView.findViewById<TextView>(R.id.tv_deviceName)
        val iv_operation = itemView.findViewById<ImageView>(R.id.iv_operation)
        val iv_camera_preview = itemView.findViewById<ImageView>(R.id.iv_camera_preview)
    }
}